

#import "GroupListViewController.h"

#import "GroupTableViewCell.h"
#import "SingleChatViewController.h"
#import "CreateGroupViewController.h"
#import "RealtimeSearchUtil.h"
#import "UIViewController+SearchController.h"

@interface GroupListViewController ()<EMSearchControllerDelegate, EMGroupManagerDelegate,EMClientDelegate>{
    EMConnectionState _connectionState;
}
@property (nonatomic, strong) UIView *networkStateView;
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (strong ,nonatomic)NSMutableArray *countArr;
@property (nonatomic,copy)NSString *cursor;
@end

@implementation GroupListViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"我的群组";
    self.page = 1;
    self.cursor = @"";
    self.showRefreshHeader = YES;
    
    [self setupSearchController];
    [self networkStateView];
    
    // Registered as SDK delegate
    [[EMClient sharedClient].groupManager removeDelegate:self];
    [[EMClient sharedClient].groupManager addDelegate:self delegateQueue:nil];
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataSource) name:@"reloadGroupList" object:nil];
   
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
     [self reloadDataSource];
}


- (void)dealloc
{
    [[EMClient sharedClient].groupManager removeDelegate:self];
    [[EMClient sharedClient] removeDelegate:self];
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [self cancelSearch];
}

//- (void)getOrganization{
//    NSArray *companyModelArr = [DataCenter shareInstence].companyList;
//    CompanyModel *model = companyModelArr.firstObject;
//    NSMutableDictionary * paramDict = [[NSMutableDictionary alloc] init];
//    [paramDict setValue:model.companyId forKey:@"companyId"];
//    [paramDict setValue:[DataCenter shareInstence].loginName forKey:@"loginName"];
//    [ZLHXHelper postURL:@"organization/group" paramDict:paramDict completion:^(NSDictionary *responseObject) {
//        NSLog(@"fdghjkl;");
//
//    } error:^(NSError *error) {
//
//
//
//    }];
//
//}


#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [self.dataSource count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    GroupTableViewCell *groupCell = [GroupTableViewCell cellWithTableView:tableView];
    
        EMGroup *group = [self.dataSource objectAtIndex:indexPath.row];
    
        if (group.subject && group.subject.length > 0) {
            groupCell.nameLable.text = group.subject;
        }
        else {
            groupCell.nameLable.text = group.groupId;
        }
 //用户期望(不要放太耗时操作)  QOS_CLASS_USER_INITIATED
//实用工具(耗时操作，可以使用这个选项)QOS_CLASS_UTILITY
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0), ^{
        
        EMGroup *group1 = [[EMClient sharedClient].groupManager getGroupSpecificationFromServerWithId:group.groupId error:nil];
        dispatch_async(dispatch_get_main_queue(), ^{
        //群成员列表
        groupCell.countL.text = [NSString stringWithFormat:@"%ld%@", group1.occupantsCount,@"人"];
        });
    });
    

    
    return groupCell;
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 64;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
        EMGroup *group = [self.dataSource objectAtIndex:indexPath.row];
    SingleChatViewController *groupChatVC = [[SingleChatViewController alloc] initWithConversationChatter:group.groupId conversationType:EMConversationTypeGroupChat];
    
    if (!group.subject) {
        groupChatVC.groupName = group.groupId;
    }else{
        
        groupChatVC.groupName = group.subject;
    }
    
        [self.navigationController pushViewController:groupChatVC animated:YES];
    
}


#pragma mark - EMGroupManagerDelegate

- (void)didUpdateGroupList:(NSArray *)groupList
{
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:groupList];
    [self.tableView reloadData];
}
                                                       
#pragma mark - EMSearchControllerDelegate
                                                       
- (void)willSearchBegin
{
    [self tableViewDidFinishTriggerHeader:YES reload:NO];
}
                                                       
- (void)cancelButtonClicked
{
    [[RealtimeSearchUtil currentUtil] realtimeSearchStop];
}
                                               
- (void)searchTextChangeWithString:(NSString *)aString
{
    __weak typeof(self) weakSelf = self;
    [[RealtimeSearchUtil currentUtil] realtimeSearchWithSource:self.dataSource searchText:aString collationStringSelector:@selector(subject) resultBlock:^(NSArray *results) {
        if (results) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.resultController.displaySource removeAllObjects];
                [weakSelf.resultController.displaySource addObjectsFromArray:results];
                [weakSelf.resultController.tableView reloadData];
            });
        }
    }];
}

#pragma mark - private

- (void)setupSearchController
{
    [self enableSearchController];
    
    __weak GroupListViewController *weakSelf = self;
    [self.resultController setCellForRowAtIndexPathCompletion:^UITableViewCell *(UITableView *tableView, NSIndexPath *indexPath) {
        
        GroupTableViewCell *cell = [GroupTableViewCell cellWithTableView:tableView];
        
        EMGroup *group = [weakSelf.resultController.displaySource objectAtIndex:indexPath.row];
        
        cell.nameLable.text = group.subject;
        //群成员列表
        cell.countL.text = [NSString stringWithFormat:@"%ld",group.occupants.count];

        return cell;
    }];

    [self.resultController setHeightForRowAtIndexPathCompletion:^CGFloat(UITableView *tableView, NSIndexPath *indexPath) {
        return 64;
    }];

    [self.resultController setDidSelectRowAtIndexPathCompletion:^(UITableView *tableView, NSIndexPath *indexPath) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];

        EMGroup *group = [weakSelf.resultController.displaySource objectAtIndex:indexPath.row];
      SingleChatViewController  *groupChatVC = [[SingleChatViewController alloc] initWithConversationChatter:group.groupId conversationType:EMConversationTypeGroupChat];
        
        if (!group.subject) {
            groupChatVC.groupName = group.groupId;
        }else{
            groupChatVC.groupName = group.subject;
        }
        
        [weakSelf.navigationController pushViewController:groupChatVC animated:YES];
                                               
        [weakSelf cancelSearch];
    }];
    
    UISearchBar *searchBar = self.searchController.searchBar;
    [self.view addSubview:searchBar];
    self.tableView.frame = CGRectMake(0, searchBar.frame.size.height, self.view.frame.size.width,self.view.frame.size.height - searchBar.frame.size.height);
}
                                                       
#pragma mark - data

- (void)tableViewDidTriggerHeaderRefresh
{
    self.page = 1;
    [self fetchGroupsWithPage:self.page isHeader:YES];
}

- (void)tableViewDidTriggerFooterRefresh
{
    self.page += 1;
    [self fetchGroupsWithPage:self.page isHeader:NO];
}

- (void)fetchGroupsWithPage:(NSInteger)aPage
                   isHeader:(BOOL)aIsHeader
{
    [self hideHud];
    [self showHudInView:self.view hint:NSLocalizedString(@"数据加载中...", @"数据加载中...")];
    
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        EMError *error = nil;
        NSArray *groupList = [[EMClient sharedClient].groupManager getJoinedGroupsFromServerWithPage:aPage pageSize:50 error:&error];
        [weakSelf tableViewDidFinishTriggerHeader:aIsHeader reload:NO];
        
        if (weakSelf)
        {
            GroupListViewController *strongSelf = weakSelf;
            dispatch_async(dispatch_get_main_queue(), ^{
                [strongSelf hideHud];
                
                if (!error)
                {
                    if (aIsHeader) {
                        NSMutableArray *oldChatrooms = [weakSelf.dataSource mutableCopy];
                        [weakSelf.dataSource removeAllObjects];
                        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                            [oldChatrooms removeAllObjects];
                        });
                    }
                    
                    [strongSelf.dataSource addObjectsFromArray:groupList];
                    [strongSelf.tableView reloadData];
                    if (groupList.count == 50) {
                        strongSelf.showRefreshFooter = YES;
                    } else {
                        strongSelf.showRefreshFooter = NO;
                    }
                }
            });
        }
    });
}

- (void)reloadDataSource
{
    [self.dataSource removeAllObjects];
    
//    从内存中获取所有群组，第一次从数据库加载
    //刷新数据
    [self.tableView.mj_header beginRefreshing];
    
    //缓存(无网环境下可以有数据)
    NSArray *groupList = [[EMClient sharedClient].groupManager getJoinedGroups];
    if (groupList.count ) {
        //        [[EMClient sharedClient].groupManager getJoinedGroupsFromServerWithPage:0 pageSize:5 completion:^(NSArray *aList, EMError *aError) {
//            if (!aError) {
//
//                [self.dataSource addObjectsFromArray:aList];
//
//                [self.tableView reloadData];
//            }
//
//        }];
//
        
        [self.dataSource addObjectsFromArray:groupList];
        
        [self.tableView reloadData];
    }
    
//    for (EMGroup *group in self.dataSource) {
//
//        //群组成员需要掉这个方法
//        EMCursorResult* result = [[EMClient sharedClient].groupManager getGroupMemberListFromServerWithId:group.groupId cursor:self.cursor pageSize:50 error:nil];
//        self.cursor = result.cursor;
//
//    }
    
   
}

#pragma mark - EMClientDelegate
// 网络状态变化回调
- (void)didConnectionStateChanged:(EMConnectionState)connectionState
{
    [self networkChanged:connectionState];
}



- (void)networkChanged:(EMConnectionState)connectionState
{
    if (connectionState == EMConnectionDisconnected) {
        self.tableView.tableHeaderView = _networkStateView;
    }
    else{
        self.tableView.tableHeaderView = nil;
    }
}


#pragma mark - getter

- (UIView *)networkStateView
{
    if (_networkStateView == nil) {
        _networkStateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.tableView.frame.size.width, 44)];
        _networkStateView.backgroundColor = [UIColor colorWithRed:255 / 255.0 green:199 / 255.0 blue:199 / 255.0 alpha:0.5];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, (_networkStateView.frame.size.height - 20) / 2, 20, 20)];
        imageView.image = [UIImage imageNamed:@"messageSendFail"];
        [_networkStateView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame) + 5, 0, _networkStateView.frame.size.width - (CGRectGetMaxX(imageView.frame) + 15), _networkStateView.frame.size.height)];
        label.font = [UIFont systemFontOfSize:15.0];
        label.textColor = [UIColor grayColor];
        label.backgroundColor = [UIColor clearColor];
        label.text = NSLocalizedString(@"网络断开连接", @"网络断开连接");
        [_networkStateView addSubview:label];
    }
    
    return _networkStateView;
}

- (NSMutableArray *)dataSource{
    if(!_dataSource) {
        _dataSource = [[NSMutableArray alloc] init];
    }
    return _dataSource;
}

- (NSMutableArray *)countArr{
    if(!_countArr) {
        _countArr = [[NSMutableArray alloc] init];
    }
    return _countArr;
}

@end
